import { ApiResponse, User, UserProfile } from '@/types/data'
import { RootThunkAction } from '@/types/store'
import request from '@/utils/request'

export function getUser(): RootThunkAction {
  return async (dispatch) => {
    const res = await request.get<ApiResponse<User>>('/user')
    // console.log(res)
    dispatch({
      type: 'profile/getUser',
      payload: res.data.data,
    })
  }
}
// 取用户信息
export const getUserProfile = (): RootThunkAction => {
  return async (dispath) => {
    const res = await request.get<ApiResponse<UserProfile>>('/user/profile')
    dispath({
      type: 'profile/getUserProfile',
      payload: res.data.data,
    })
  }
}

// 修改昵称和简介
export const updateUserProfile = (
  key: string,
  value: string
): RootThunkAction => {
  return async (dispatch) => {
    await request.patch('/user/profile', { [key]: value })
    // 重新获取用户信息
    dispatch(getUserProfile())
  }
}

export function updateUserPhoto(fd: FormData): RootThunkAction {
  return async (dispatch) => {
    await request.patch('/user/photo', fd)
    await dispatch(getUserProfile())
  }
}
